package com.example.software.exception;

import com.example.software.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理参数校验异常
     * @param e 异常
     * @return 返回结果
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder sb = new StringBuilder("参数校验失败：");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sb.append(fieldError.getField()).append("：").append(fieldError.getDefaultMessage()).append(", ");
        }
        String msg = sb.toString();
        log.error(msg, e);
        return Result.error(400, msg);
    }

    /**
     * 处理JSON解析异常
     * @param e 异常
     * @return 返回结果
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result<Void> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.error("JSON解析异常：", e);
        
        String errorMessage = "请求数据格式错误";
        
        // 获取更具体的错误原因
        String message = e.getMessage();
        if (message != null) {
            if (message.contains("Unrecognized field")) {
                // 找出不支持的字段名
                int startIndex = message.indexOf("Unrecognized field \"") + 19;
                int endIndex = message.indexOf("\"", startIndex);
                if (startIndex > 0 && endIndex > startIndex) {
                    String fieldName = message.substring(startIndex, endIndex);
                    errorMessage = "不支持的字段: " + fieldName;
                }
            } else if (message.contains("Cannot deserialize")) {
                errorMessage = "数据类型转换错误，请检查请求数据";
            }
        }
        
        return Result.error(400, errorMessage);
    }

    /**
     * 处理运行时异常
     * @param e 异常
     * @return 返回结果
     */
    @ExceptionHandler(RuntimeException.class)
    public Result<Void> handleRuntimeException(RuntimeException e) {
        log.error("运行时异常：", e);
        return Result.error(e.getMessage());
    }

    /**
     * 处理未知异常
     * @param e 异常
     * @return 返回结果
     */
    @ExceptionHandler(Exception.class)
    public Result<Void> handleException(Exception e) {
        log.error("系统异常：", e);
        return Result.error("系统异常，请联系管理员");
    }
} 